package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wjs
 * @version 1.0
 * @date 2021/12/26 0026 下午 6:38
 */

@DubboService
public class MovementServiceImpl implements MovementApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    @Override
    public Movement publish(Movement movement) {
        //设置PID
        movement.setPid(idWorker.getNextId("movement"));
        //设置时间
        movement.setCreated(System.currentTimeMillis());
        //保存数据
        mongoTemplate.save(movement);

        timeLineService.saveTimeLine(movement.getUserId(), movement.getId());

        return movement;
    }

    @Override
    public PageResult pageByUserId(Long userId, Integer page, Integer pagesize) {

        Query query = new Query(Criteria.where("userId").is(userId).and("state").is(1));

        //查询总记录数
        long count = mongoTemplate.count(query, Movement.class);
        //设置分页查询参数
        query.skip((page -1 ) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //查询分页数据列表
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        //构造返回值
        return new PageResult(page,pagesize,count,movements);
    }

    @Override
    public List<Movement> findFriendMovements(Integer page, Integer pagesize, Long userId) {
        //根据userId查询时间线表,获取userId对应的friend
        Query query = Query.query(Criteria.where("friendId").is(userId).and("state").is(1))
                .skip((page -1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> lineList = mongoTemplate.find(query, MovementTimeLine.class);
        //提取动态id列表
        List<ObjectId> list = lineList.stream().map(movementTimeLine -> movementTimeLine.getMovementId()).collect(Collectors.toList());
        //根据动态id查询动态详情
        Query movementQuery = Query.query(Criteria.where("id").in(list));
        return mongoTemplate.find(movementQuery,Movement.class);
    }

    @Override
    public List<Movement> randomMovents(Integer counts, Long userId) {

        //1、创建统计对象，设置统计参数
        //Movement.class映射数据库表,Aggregation.sample(counts)随机产生counts个数据(第二个参数产生 方法)
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(counts),Aggregation.match(Criteria.where("userId").nin(userId).and("state").is(1)));
        //2、调用mongoTemplate方法统计
        //Movement.class对应实体对象,确定返回值
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //3、获取统计结果
        return results.getMappedResults();
    }

    @Override
    public List<Movement> findMovementsByPids(List<Long> pids) {
        Query query = Query.query(Criteria.where("pid").in(pids).and("state").is(1));
        return mongoTemplate.find(query,Movement.class);
    }

    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId, Movement.class);
    }

    @Override
    public PageResult findPageByUserIdAndState(Integer page, Integer pagesize, Long uid, Integer state) {

        Query query = new Query();
        if(uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if(state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        long count = mongoTemplate.count(query, Movement.class);

        query.skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);

        return new PageResult(page,pagesize,count,movements);
    }

    @Override
    public void update(String movementId, Integer state) {
        Query query = Query.query(Criteria.where("id").in(new ObjectId(movementId)));
        Update update = Update.update("state", state);
        mongoTemplate.updateFirst(query, update, Movement.class);
    }
}
